package com.example.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by hldev on 16-12-15.
 */
public class Encrypt {

    public static String encryptStrWithMD5(String str) {
        String encryptCode = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            encryptCode = new BigInteger(1, md.digest()).toString(16);

        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        } finally {
            return encryptCode;
        }
    }

    public static String getSalt() {
        String baseCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        char[] rands = new char[6];
        for(int i = 0; i < 6; i++) {
            int rand = (int)(Math.random() * baseCode.length());
            rands[i] = baseCode.charAt(rand);
        }
        return new String(rands);
    }

    public static String encryptStrWithBase64(String str) {
        String encryptCode = null;
        BASE64Encoder base64Encoder = new BASE64Encoder();
        encryptCode = base64Encoder.encode(str.getBytes());
        return encryptCode;
    }

    public static String decryptStrWithBase64(String str) throws Exception{
        String decryptCode = null;
        BASE64Decoder base64Decoder = new BASE64Decoder();
        decryptCode = new String(base64Decoder.decodeBuffer(str));
        return decryptCode;
    }

}
